import { useState } from "react";
import { useQuery, useMutation } from "@tanstack/react-query";
import { useForm } from "react-hook-form";
import { zodResolver } from "@hookform/resolvers/zod";
import { Card, CardContent, CardHeader, CardTitle } from "@/components/ui/card";
import { Button } from "@/components/ui/button";
import { Input } from "@/components/ui/input";
import { Label } from "@/components/ui/label";
import { Textarea } from "@/components/ui/textarea";
import { 
  Select,
  SelectContent,
  SelectItem,
  SelectTrigger,
  SelectValue,
} from "@/components/ui/select";
import { Switch } from "@/components/ui/switch";
import { Plus, Edit, Trash2 } from "lucide-react";
import { ProxyRulesTable } from "@/components/proxy-rules-table";
import { insertProxyRuleSchema, ProxyRule } from "@shared/schema";
import { apiRequest, queryClient } from "@/lib/queryClient";
import { useToast } from "@/hooks/use-toast";
import { z } from "zod";

const formSchema = insertProxyRuleSchema.extend({
  type: z.enum(["HTTP", "HTTPS", "TCP", "UDP"]),
  loadBalancing: z.enum(["round-robin", "least-connections", "ip-hash"]),
});

type FormData = z.infer<typeof formSchema>;

export default function ProxyConfig() {
  const [isFormOpen, setIsFormOpen] = useState(false);
  const [editingRule, setEditingRule] = useState<ProxyRule | null>(null);
  const { toast } = useToast();

  const {
    register,
    handleSubmit,
    reset,
    setValue,
    watch,
    formState: { errors },
  } = useForm<FormData>({
    resolver: zodResolver(formSchema),
    defaultValues: {
      name: "",
      description: "",
      type: "HTTP",
      localPort: 8080,
      remotePort: 80,
      targetHost: "localhost",
      status: "stopped",
      loadBalancing: "round-robin",
      healthCheck: true,
    },
  });

  const createProxyMutation = useMutation({
    mutationFn: (data: FormData) => apiRequest("POST", "/api/proxy-rules", data),
    onSuccess: () => {
      queryClient.invalidateQueries({ queryKey: ["/api/proxy-rules"] });
      toast({ title: "代理规则创建成功" });
      reset();
      setIsFormOpen(false);
    },
    onError: () => {
      toast({ title: "创建失败", variant: "destructive" });
    },
  });

  const updateProxyMutation = useMutation({
    mutationFn: ({ id, data }: { id: number; data: Partial<FormData> }) => 
      apiRequest("PUT", `/api/proxy-rules/${id}`, data),
    onSuccess: () => {
      queryClient.invalidateQueries({ queryKey: ["/api/proxy-rules"] });
      toast({ title: "代理规则更新成功" });
      reset();
      setIsFormOpen(false);
      setEditingRule(null);
    },
    onError: () => {
      toast({ title: "更新失败", variant: "destructive" });
    },
  });

  const onSubmit = (data: FormData) => {
    if (editingRule) {
      updateProxyMutation.mutate({ id: editingRule.id, data });
    } else {
      createProxyMutation.mutate(data);
    }
  };

  const handleEdit = (rule: ProxyRule) => {
    setEditingRule(rule);
    setValue("name", rule.name);
    setValue("description", rule.description || "");
    setValue("type", rule.type as "HTTP" | "HTTPS" | "TCP" | "UDP");
    setValue("localPort", rule.localPort);
    setValue("remotePort", rule.remotePort);
    setValue("targetHost", rule.targetHost);
    setValue("loadBalancing", rule.loadBalancing as "round-robin" | "least-connections" | "ip-hash");
    setValue("healthCheck", rule.healthCheck);
    setIsFormOpen(true);
  };

  const handleCancel = () => {
    reset();
    setEditingRule(null);
    setIsFormOpen(false);
  };

  return (
    <div className="flex-1 overflow-hidden">
      {/* Header */}
      <header className="bg-white border-b border-slate-200 px-6 py-4">
        <div className="flex items-center justify-between">
          <div>
            <h2 className="text-2xl font-semibold text-slate-800">代理配置</h2>
            <p className="text-slate-600">管理和配置反向代理规则</p>
          </div>
          <Button 
            onClick={() => setIsFormOpen(true)}
            className="bg-primary hover:bg-blue-700"
          >
            <Plus className="w-4 h-4 mr-2" />
            新建代理规则
          </Button>
        </div>
      </header>

      <div className="p-6 overflow-y-auto h-full space-y-6">
        {/* Configuration Form */}
        {isFormOpen && (
          <Card>
            <CardHeader>
              <CardTitle>
                {editingRule ? "编辑代理规则" : "新建代理规则"}
              </CardTitle>
            </CardHeader>
            <CardContent>
              <form onSubmit={handleSubmit(onSubmit)} className="space-y-6">
                <div className="grid grid-cols-1 md:grid-cols-2 gap-6">
                  <div className="space-y-2">
                    <Label htmlFor="name">规则名称 *</Label>
                    <Input
                      id="name"
                      placeholder="例如: web-server"
                      {...register("name")}
                    />
                    {errors.name && (
                      <p className="text-sm text-red-600">{errors.name.message}</p>
                    )}
                  </div>

                  <div className="space-y-2">
                    <Label htmlFor="type">协议类型 *</Label>
                    <Select 
                      value={watch("type")} 
                      onValueChange={(value) => setValue("type", value as "HTTP" | "HTTPS" | "TCP" | "UDP")}
                    >
                      <SelectTrigger>
                        <SelectValue />
                      </SelectTrigger>
                      <SelectContent>
                        <SelectItem value="HTTP">HTTP</SelectItem>
                        <SelectItem value="HTTPS">HTTPS</SelectItem>
                        <SelectItem value="TCP">TCP</SelectItem>
                        <SelectItem value="UDP">UDP</SelectItem>
                      </SelectContent>
                    </Select>
                  </div>

                  <div className="space-y-2">
                    <Label htmlFor="localPort">本地端口 *</Label>
                    <Input
                      id="localPort"
                      type="number"
                      placeholder="8080"
                      {...register("localPort", { valueAsNumber: true })}
                    />
                    {errors.localPort && (
                      <p className="text-sm text-red-600">{errors.localPort.message}</p>
                    )}
                  </div>

                  <div className="space-y-2">
                    <Label htmlFor="remotePort">远程端口 *</Label>
                    <Input
                      id="remotePort"
                      type="number"
                      placeholder="80"
                      {...register("remotePort", { valueAsNumber: true })}
                    />
                    {errors.remotePort && (
                      <p className="text-sm text-red-600">{errors.remotePort.message}</p>
                    )}
                  </div>

                  <div className="space-y-2">
                    <Label htmlFor="targetHost">目标主机</Label>
                    <Input
                      id="targetHost"
                      placeholder="localhost"
                      {...register("targetHost")}
                    />
                  </div>

                  <div className="space-y-2">
                    <Label htmlFor="loadBalancing">负载均衡策略</Label>
                    <Select 
                      value={watch("loadBalancing")} 
                      onValueChange={(value) => setValue("loadBalancing", value as "round-robin" | "least-connections" | "ip-hash")}
                    >
                      <SelectTrigger>
                        <SelectValue />
                      </SelectTrigger>
                      <SelectContent>
                        <SelectItem value="round-robin">轮询</SelectItem>
                        <SelectItem value="least-connections">最少连接</SelectItem>
                        <SelectItem value="ip-hash">IP哈希</SelectItem>
                      </SelectContent>
                    </Select>
                  </div>
                </div>

                <div className="space-y-2">
                  <Label htmlFor="description">描述</Label>
                  <Textarea
                    id="description"
                    placeholder="代理规则的详细描述"
                    {...register("description")}
                  />
                </div>

                <div className="flex items-center space-x-2">
                  <Switch 
                    id="healthCheck"
                    checked={watch("healthCheck")}
                    onCheckedChange={(checked) => setValue("healthCheck", checked)}
                  />
                  <Label htmlFor="healthCheck">启用健康检查</Label>
                </div>

                <div className="flex items-center justify-end space-x-4">
                  <Button type="button" variant="outline" onClick={handleCancel}>
                    取消
                  </Button>
                  <Button 
                    type="submit" 
                    disabled={createProxyMutation.isPending || updateProxyMutation.isPending}
                    className="bg-primary hover:bg-blue-700"
                  >
                    {editingRule ? "更新" : "创建"}
                  </Button>
                </div>
              </form>
            </CardContent>
          </Card>
        )}

        {/* Proxy Rules Table */}
        <ProxyRulesTable />
      </div>
    </div>
  );
}
